package com.bsg.upm.aspect;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONArray;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.http.RespJson;

/**
 * 日志切面类
 * 
 * @author HCK
 *
 */
@Aspect
@Component
public class LogAspect {

	protected Logger logger = Logger.getLogger(getClass());

	@Pointcut("execution(public * com.bsg.upm.controller.*.*(..)) ")
	public void pointcut() {

	}

	@Before("pointcut()")
	public void doBefore(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String targetName = joinPoint.getTarget().getClass().getName();
		String methodName = joinPoint.getSignature().getName();
		String params = "";
		if (joinPoint.getArgs() != null) {
			for (int i = 0; i < joinPoint.getArgs().length; i++) {
				params += joinPoint.getArgs()[i] + ";";
			}
		}

		HttpSession session = request.getSession();
		UserEntity user = (UserEntity) session.getAttribute("user");
		String username = "";
		if (user != null) {
			username = user.getUsername();
		}
		logger.info("[" + username + "] - WEB请求地址：" + request.getServletPath());
		logger.info("[" + username + "] - WEB请求类型：" + request.getMethod());
		logger.info("[" + username + "] - WEB请求方法：" + targetName + "." + methodName + "()");
		logger.info("[" + username + "] - WEB请求参数：" + params);
	}

	@AfterReturning(pointcut = "pointcut()", returning = "rvt")
	public void doAfterReturning(JoinPoint joinPoint, Object rvt) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession();
		UserEntity user = (UserEntity) session.getAttribute("user");
		String username = "";
		if (user != null) {
			username = user.getUsername();
		}
		boolean bigData = false;
		if (rvt instanceof RespJson) {
			Object data = ((RespJson) rvt).getData();
			if (data instanceof JSONArray) {
				if (((JSONArray) data).size() > 500) {
					bigData = true;
				}
			}
		}
		if (bigData) {
			logger.info("[" + username + "] - WEB请求结果：数据量过大...\r\n");
		} else {
			logger.info("[" + username + "] - WEB请求结果：" + rvt + "\r\n");
		};
	}
}
